$(function () {
    layui.use(['table', 'laydate', 'form','dropdown'], function () {
        table = layui.table
        dropdown=layui.dropdown
        var laydate = layui.laydate, $ = layui.$;
        form = layui.form;

        //type1
        let MyType1=[]
        $('#type1').attr("disabled", true);
        AjaxGet("/jzweb/jazSignupGroup/list").then(function (response) {
            //设置select
            $('#type1').empty();
            $('#type1').append($('<option>', {
                value: '',
                text: '请选择所属组别'
            }))
            MyType1=[]
            response.data.forEach(item => {
                $('#type1').append($('<option>', {
                    value: item.id,
                    text: item.name
                }))
                MyType1.push({
                    value: item.id,
                    text: item.name
                })
            })
            $('#type1').attr("disabled", false);
            form.render('select');
        }).catch(function (error) {
            layer.msg(error.msg)
        })


        form.on('select(type1)', function(data){
            var elem = data.elem; // 获得 select 原始 DOM 对象
            var value = data.value; // 获得被选中的值
            $('#type2').attr("disabled", true);
            $('#type2').empty();
            if(value){
                //type2
                $('#type2').attr("disabled", true);
                AjaxGet(`/jzweb/jazSignupItem/list?groupId=${value}`).then(function (response) {
                    $('#type2').empty();
                    $('#type2').append($('<option>', {
                        value: '',
                        text: '请选择参赛项目类型'
                    }))
                    response.data.forEach(item => {
                        $('#type2').append($('<option>', {
                            value: item.id,
                            text: item.name
                        }))
                    })

                    $('#type2').attr("disabled", false);
                    form.render('select');
                }).catch(function (error) {
                    layer.msg(error.msg)
                })
            }else{
                $('#type2').append($('<option>', {
                    value: '',
                    text: '请先选择所属组别'
                }))
            }
            $('#type2').attr("disabled", false);
            form.render('select');

        });


        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            , url: '/jzweb/jazSignupResult/list'
            ,method:'get'
            ,contentType: 'application/x-www-form-urlencoded'
            // ,contentType: 'application/json'
            , cellMinWidth: 100
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 15
                , limits : [15,30,50,100,200]
            }
            , request: {
                pageName: 'curr' //页码的参数名称，默认：page
                , limitName: 'pageSize'
            }
            , where: myWhere
            , defaultToolbar: false
            , loading: false
            , cols:myCols
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) {
                dropdownButtonNumber=0
                if (res.code != 0) {
                    return false;
                }
                if(Number(res.data.total)>0&&res.data.records.length==0){
                    pages--;
                    if(pages>0) {
                        table.reload('exampleTable', {
                            page: {curr: pages},
                            where: myWhere
                        })
                    }
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {
                console.log(res, msg)
            }
            , done: function (res) {
                for (let i = 0; i < dropdownButtonNumber; i++) {
                    //可能设置更多
                    let mydata=[]
                    let mypdf= $(`.dropdownButton${i}`).attr('my-data').split(',')
                    for (let j = 0; j < mypdf.length; j++) {
                        mydata.push({
                            id:mypdf[j],
                            title: mypdf[j].substr(mypdf[j].lastIndexOf('/')+33)
                        })
                    }
                    dropdown.render({
                        elem: `.dropdownButton${i}`, // 可绑定在任意元素中，此处以上述按钮为例
                        data:mydata,
                        click: function(obj){
                            openPdfUrl(obj.id)
                        }
                    });
                }

                layer.close()
                hindLoading()
            }
        });

        var $ = layui.$, active = {
            reload: function () {
                setMyWhere()
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: myWhere
                });
            }
        };

        /**
         * 搜索事件
         */
        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            setMyWhere()
            active[type] ? active[type].call(this) : '';
        });

    });


});
let table = null,dropdown=null,dropdownButtonNumber=0;
let myWhere = {},form =null;

const setMyWhere = () => {
    myWhere = {
        groupId:$('#type1').val(),
        itemId:$('#type2').val(),
    }
}
setMyWhere()
let myCols = [[
    {
        field: 'checkbox',
        checkbox: true
    },
        {
            field: 'groupName',
            title: '所属组别',
            width:100,
            align: 'center'
        },
        {
            field: 'itemName',
            align: 'center',
            width:150,
            title: '参赛项目'
        },
        {
            field: 'name',
            align: 'center',
            width:250,
            title: '公示表名称'
        },
        {
            field: 'file',
            align: 'center',
            title: '成绩公示表',
            templet : function(d) {
                let myWidth=$("th[title='成绩公示表']")[0].offsetWidth
                let wnumber=0,spanWidth=0
                let myFiles=[] ,str='',name=''
                if(d.file){
                    myFiles=d.file.split(',')
                    for (let i = 0; i < myFiles.length; i++) {
                        name=myFiles[i].substr(myFiles[i].lastIndexOf('/')+33)
                        str+=`<a class="myA" href="#"> <span onclick="openPdfUrl('${myFiles[i]}')">${name}</span></a>`
                        spanWidth+=calculateTextWidth(name)+20
                        if(myWidth>spanWidth){wnumber++;}
                    }
                }
                if(wnumber>=myFiles.length){
                    return  str
                }else{
                    str=''
                    for (let i = 0; i < (wnumber - 1); i++) {
                        name=myFiles[i].substr(myFiles[i].lastIndexOf('/')+33)
                        str+=`<a class="myA" href="#"> <span onclick="openPdfUrl('${myFiles[i]}')" >${name}</span></a>`
                    }
                    //获取数据
                    let oth=myFiles.slice(wnumber-myFiles.length-1).join(',')
                    str+=`
                    <a class="myA" href="#">
                      <span class="dropdownButton${dropdownButtonNumber++}" my-data="${oth}">
                          更多数据
                        <i class="layui-icon layui-icon-down layui-font-12"></i>
                     </span>
                     </a>
                    `

                }
                return  str
            }
        },
        {
            field: 'createTime',
            align: 'center',
            width:150,
            title: '上传时间',
        },
        {
            field: 'auditStatus',
            align: 'center',
            title: '操作',
            width:100,
            templet : function(d) {
                // var e = '<a  class="btn btn-primary btn-sm '+look_info+'" href="#" mce_href="#" title="详情" onclick="lookInfo(\''
                //     + d.id
                //     + '\' )"><i class="fa fa-send"></i></a> ';

                var ss = '<a class="btn btn-success btn-sm '+look_remove+'" href="#" title="删除"  mce_href="#" onclick="remove(\''
                    + d.id
                    + '\')"><i class="fa fa-remove"></i></a>';
                return   ss;
            }
        },
    ]]
// /**
//  * 动态宽度
//  */
// $(window).on('resize', function() {
//     // 窗口尺寸变化时重新计算和设置宽度
//     let containerWidth = $("td[data-field='file']")[0].offsetWidth;
//     let wnumber=Math.floor(myWidth / 100)
// });

/**
 * 重置
 */
const dataReset = () => {
    $("#type1").val('')
    form.render('select');
    setMyWhere()
    table.reload('exampleTable', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        , where: myWhere
    });
}
let pages = 1;

/**
 * 所有的重置表格
 */
function load(){
    layui.use(['table'], ()=>{
        layui.table.reload('exampleTable',{
            where: myWhere
        })
    })
}

function calculateTextWidth(text) {
    let spanElement=document.getElementsByTagName('body')[0]
    var tempSpan = document.createElement('span');
    tempSpan.textContent = text;
    spanElement.appendChild(tempSpan);

    // 计算临时元素的宽度
    var width = tempSpan.offsetWidth;

    // 删除临时元素
    spanElement.removeChild(tempSpan);

    // 返回宽度
    return width;
}

/**
 * 新增
 */
let myPdf=[],myPdfItem = {name: '', url: '', id: ''}
var openPdf = (id) => {
    let myItem = myPdf.find(item => item.id == id + '-0')
    if (myItem) {
        if(myItem.contractType==0){
            let a= document.createElement("a");
            a.href=`/jzApi/jazUserAunt/userOrderExport?orderId=${myItem?.orderId}`
            a.download="合同.docx"
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            return false;
        }
        openPdfUrl(myItem.url)
    }
}
var openPdfUrl = (url) => {
        let toIndex = layer.open({
            type: 2,
            area: ['80%', '80%'],
            fixed: false, //不固定
            maxmin: true,
            content: url
        });
}
var removeImg= (id) => {
        if (myPdf.find(item => item.id == id + '-0')) {
            //删除这条
            myPdf = myPdf.filter((item) => {
                return !(id + '-0').includes(item.id)
            });
            $('#myUpdataList').find('div[myid=' + id + '-0]').remove();
        }
    event.stopPropagation();
}
const add=()=>{
    const toIndex=layer.open({
        type: 1,
        area: ['500px', '450px'],
        title: '新增成绩公示表',
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">  
   <div class="layui-form-item">  
      <label class="layui-form-label required">所属组别</label>
      <div class="layui-input-block">
       <select name="groupId" id="type3"  lay-filter="type3">
                            <option value="">请选择所属组别</option>
        </select>
      </div>
   </div>
    <div class="layui-form-item">   
      <label class="layui-form-label required">参赛项目</label>
      <div class="layui-input-block"> 
                        <select name="itemId" id="type4">
                            <option value="">请先选择所属组别</option>
                        </select> 
      </div>
   </div> 
    <div class="layui-form-item">   
      <label class="layui-form-label required">公示表名称</label>
      <div class="layui-input-block"> 
      <input class="input layui-input" type="text" name="name" property="请输入公示表名称"> 
      </div>
   </div> 
    <div class="layui-form-item"> 
      <label class="layui-form-label required">成绩公示表</label>
      <div class="layui-input-block" id="myUpdataList" style="display: flex;  align-items: center;  flex-direction: row;flex-wrap: wrap;"> 
                    <div  id="myUpdata" style="margin:5px 10px; cursor: pointer;width: 100px;height: 100px;background-color: transparent;display: flex; justify-content: center; align-items: center; border: 1px solid #000;"> 
                            <span>支持PDF</span> 
                    </div> 
      </div>
   </div>
   
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="btn btn-success" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form> 
                `,
        success: (layero, index) => {
                myPdf=[]
                layui.use(['form','laydate','upload'], () => {
                    var   form = layui.form,upload = layui.upload;
                //type1
                let MyType1=[]
                $('#type3').attr("disabled", true);
                $.ajax({
                    type: 'get',
                    url: '/jzweb/jazSignupGroup/list',
                    success:  (response)=> {
                        if (response.code == "0") {
                                //设置select
                                $('#type3').empty();
                                $('#type3').append($('<option>', {
                                    value: '',
                                    text: '请选择所属组别'
                                }))
                                MyType1=[]
                                response.data.forEach(item => {
                                    $('#type3').append($('<option>', {
                                        value: item.id,
                                        text: item.name
                                    }))
                                    MyType1.push({
                                        value: item.id,
                                        text: item.name
                                    })
                                })
                                $('#type3').attr("disabled", false);
                                form.render('select');
                        } else {
                            layer.msg(r.msg);
                        }
                    }
                })
                form.on('select(type3)', function(data){
                    var elem = data.elem; // 获得 select 原始 DOM 对象
                    var value = data.value; // 获得被选中的值
                    $('#type4').attr("disabled", true);
                    $('#type4').empty();
                    if(value){
                        //type2
                        $('#type4').attr("disabled", true);
                        $.ajax({
                            type: 'get',
                            url: `/jzweb/jazSignupItem/list?groupId=${value}`,
                            success:  (response)=> {
                            $('#type4').append($('<option>', {
                                value: '',
                                text: '请选择参赛项目类型'
                            }))
                            response.data.forEach(item => {
                                $('#type4').append($('<option>', {
                                    value: item.id,
                                    text: item.name
                                }))
                            })

                            $('#type4').attr("disabled", false);
                            form.render('select');
                        }
                        })
                    }else{
                        $('#type4').append($('<option>', {
                            value: '',
                            text: '请先选择所属组别'
                        }))
                    }
                    $('#type4').attr("disabled", false);
                    form.render('select');

                });
                form.render('select');

                //
               upload.render({
                        elem: '#myUpdata'
                        , url: '/common/sysFile/upload'
                        , accept: 'file'
                        // , exts: 'doc|docx'
                        , exts: 'pdf'
                        // , multiple: true
                        , acceptMime: 'application/pdf'
                        // , acceptMime: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        , before: function (obj) {
                            if(myPdf.length>=1000){
                                layer.msg('上传已达上限，请删除在传')
                                return false;
                            }
                            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
                            for (var key in files) {
                                if (!myPdf.find(item => item.id == key)) {
                                    myPdfItem = {name: '', url: '', id: ''}
                                    // myPdfItem.name = files[key].name
                                    myPdfItem.name ='文件'
                                    myPdfItem.id = key
                                }
                            }
                            //读取本地文件
                            obj.preview(function (index, file, result) {
                                console.log(file.Name);
                            });
                            loading = layer.load({
                                type: 3,
                                content: '加载中...',
                            });//在post之前定义loading
                        }
                        , done: function (res, index) {
                            layer.close(loading);
                            if (res.code == 0) {
                                if(myPdf.length<1000){
                                    layer.msg('上传成功');
                                    myPdfItem.url = res.data
                                    myPdf.push(myPdfItem)
                                    delete this.files[index]
                                    $('#myUpdataList').prepend(`
				<div href="#"  style="margin:5px 10px;width: 100px;position: relative; display: flex;  flex-direction: column;  justify-content: center;  align-items: center;   
				height: 100px;border: 1px solid #000;" myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" style="    width: 50px;height: 50px" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						<a style=" position: absolute; right: 0; top: 0;width: 20px; height: 20px;" href="#" onclick="removeImg(${myPdfItem.id});"> 
						<img style="    width: inherit;height: inherit"  class="closeUpload" src="/img/close.png" >	
						</a>
				</div>
				`)
                                }else {
                                    layer.msg('上传已达上限，请删除在传')
                                }
                            } else {
                                layer.msg('上传失败,请检查');
                            }

                        }
                    })

                form.on('submit(layedit-code-yes)', (data) => {
                    const mydata = data.field
                    mydata.file=''
                    let str=''
                    for (let i = 0; i < myPdf.length; i++) {
                        str+=myPdf[i].url+','
                    }
                    mydata.file=str.substring(0,str.length-1)
                    console.log('提交数据',mydata)
                    if(''==mydata.groupId){
                        layer.msg('请选择参赛项目')
                        return false
                    }
                    if(''==mydata.itemId){
                        layer.msg('请选择参赛项目')
                        return false
                    }
                    if(''==mydata.file){
                        layer.msg('请上传成绩公示表')
                        return false
                    }
                    // //修改
                    $.ajax({
                        type: 'post',
                        data: JSON.stringify({
                            ...mydata
                        }),
                        contentType: 'application/json',
                        url: '/jzweb/jazSignupResult/save',
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg(r.msg);
                                layer.close(index)
                                load();
                            } else {
                                layer.msg(r.msg);
                            }
                        }
                    });

                });
            })


        }
    });




}

const daochu=()=>{
    var rows = table.checkStatus('exampleTable').data
    layer.confirm(rows.length>0?'确认导出选中的'+rows.length+'条数据吗？':"确认要导出表格数据吗？", {
        btn : [ '确定', '取消' ]
        // 按钮
    }, function(index, layero) {
        console.log('导出')
        //参数
        setMyWhere()
        let objkey=Object.keys(myWhere)
        let str=''
        objkey.map(item=>{
            str+=item+'='+myWhere[item]+'&'
        })
        str=str.substring(0,str.length-1)
        myDownFiles(`/jzweb/jazOrderDetail/downloadImportTemplate?${str}`)
        layer.close(index);
    }, function() {
    })
}

// function lookInfo(id){
//     sessionStorage.setItem('checkId',id);
//     let toIndex=layer.open({
//         type: 2,
//         title:'队伍详情',
//         maxmin: true,
//         shadeClose: false,
//         area:['800px','500px'],
//         content:  `/team/info/${id}`
//     });
//     layer.full(toIndex);
// }
function remove(id) {

    layer.confirm('是否删除此成绩公示？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : "/jzweb/jazSignupResult/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    load();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}